<template>
  <el-button @click="clickStart" :loading="loading" :disabled="count > 0">
    {{ formatter(count) }}
  </el-button>
</template>

<script setup name="CountDownBtn">
import { ref } from 'vue'

const props = defineProps({
  // 检测是否可开始倒计时，返回boolean，可异步
  checkCondition: {
    type: Function,
    default: () => true,
  },
  // 自定义按钮的文案，分别是初始状态与倒计时状态
  formatter: {
    type: Function,
    default: (count) => (count > 0 ? `${count}秒后重新发送` : '发送短信验证码'),
  },
  // 倒计时的最大值
  maxCount: {
    type: Number,
    default: 60,
  },
})

// 短信验证码倒计时
const loading = ref(false)
const count = ref(0)
let timer = null

// 开始倒计时
function startCountDown() {
  count.value = props.maxCount
  timer = setInterval(() => {
    count.value--
    if (count.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 检查条件，是否可开启倒计时
async function checkCondition() {
  loading.value = true
  const res = await props.checkCondition()
  loading.value = false
  if (res) {
    startCountDown()
  }
}

// 点击发送短信
async function clickStart() {
  checkCondition()
}
</script>
